/**
 *    Copyright 2006-2016 the original author or authors.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
package com.hundsun.epay.autosimu.utils;

import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 
 * @author Jeff Butler
 */
public class StringUtility {

    /**
     * Utility class. No instances allowed
     */
    private StringUtility() {
        super();
    }

    public static boolean stringHasValue(String s) {
        return s != null && s.length() > 0;
    }

    public static String composeFullyQualifiedTableName(String catalog,
            String schema, String tableName, char separator) {
        StringBuilder sb = new StringBuilder();

        if (stringHasValue(catalog)) {
            sb.append(catalog);
            sb.append(separator);
        }

        if (stringHasValue(schema)) {
            sb.append(schema);
            sb.append(separator);
        } else {
            if (sb.length() > 0) {
                sb.append(separator);
            }
        }

        sb.append(tableName);

        return sb.toString();
    }

    public static boolean stringContainsSpace(String s) {
        return s != null && s.indexOf(' ') != -1;
    }

    public static String escapeStringForJava(String s) {
        StringTokenizer st = new StringTokenizer(s, "\"", true); //$NON-NLS-1$
        StringBuilder sb = new StringBuilder();
        while (st.hasMoreTokens()) {
            String token = st.nextToken();
            if ("\"".equals(token)) { //$NON-NLS-1$
                sb.append("\\\""); //$NON-NLS-1$
            } else {
                sb.append(token);
            }
        }

        return sb.toString();
    }

    public static String escapeStringForXml(String s) {
        StringTokenizer st = new StringTokenizer(s, "\"", true); //$NON-NLS-1$
        StringBuilder sb = new StringBuilder();
        while (st.hasMoreTokens()) {
            String token = st.nextToken();
            if ("\"".equals(token)) { //$NON-NLS-1$
                sb.append("&quot;"); //$NON-NLS-1$
            } else {
                sb.append(token);
            }
        }

        return sb.toString();
    }

    public static boolean isTrue(String s) {
        return "true".equalsIgnoreCase(s); //$NON-NLS-1$
    }

    public static boolean stringContainsSQLWildcard(String s) {
        if (s == null) {
            return false;
        }

        return s.indexOf('%') != -1 || s.indexOf('_') != -1;
    }
    
    /**
     * 检查字符串是否为<code>null</code>或空字符串<code>""</code>。
     * <pre>
     * StringUtil.isEmpty(null)      = true
     * StringUtil.isEmpty("")        = true
     * StringUtil.isEmpty(" ")       = false
     * StringUtil.isEmpty("bob")     = false
     * StringUtil.isEmpty("  bob  ") = false
     * </pre>
     *
     * @param str 要检查的字符串
     *
     * @return 如果为空, 则返回<code>true</code>
     */
    public static boolean isEmpty(String str) {
        return ((str == null) || (str.length() == 0));
    }

    /**
     * 检查字符串是否不是<code>null</code>和空字符串<code>""</code>。
     * <pre>
     * StringUtil.isNotEmpty(null)      = false
     * StringUtil.isNotEmpty("")        = false
     * StringUtil.isNotEmpty(" ")       = true
     * StringUtil.isNotEmpty("bob")     = true
     * StringUtil.isNotEmpty("  bob  ") = true
     * </pre>
     *
     * @param str 要检查的字符串
     *
     * @return 如果不为空, 则返回<code>true</code>
     */
    public static boolean isNotEmpty(String str) {
        return ((str != null) && (str.length() > 0));
    }

    /**
     * 检查字符串是否是空白：<code>null</code>、空字符串<code>""</code>或只有空白字符。
     * <pre>
     * StringUtil.isBlank(null)      = true
     * StringUtil.isBlank("")        = true
     * StringUtil.isBlank(" ")       = true
     * StringUtil.isBlank("bob")     = false
     * StringUtil.isBlank("  bob  ") = false
     * </pre>
     *
     * @param str 要检查的字符串
     *
     * @return 如果为空白, 则返回<code>true</code>
     */
    public static boolean isBlank(String str) {
        int length;

        if ((str == null) || ((length = str.length()) == 0)) {
            return true;
        }

        for (int i = 0; i < length; i++) {
            if (!Character.isWhitespace(str.charAt(i))) {
                return false;
            }
        }

        return true;
    }

    /**
     * 检查字符串是否不是空白：<code>null</code>、空字符串<code>""</code>或只有空白字符。
     * <pre>
     * StringUtil.isNotBlank(null)      = false
     * StringUtil.isNotBlank("")        = false
     * StringUtil.isNotBlank(" ")       = false
     * StringUtil.isNotBlank("bob")     = true
     * StringUtil.isNotBlank("  bob  ") = true
     * </pre>
     *
     * @param str 要检查的字符串
     *
     * @return 如果为空白, 则返回<code>true</code>
     */
    public static boolean isNotBlank(String str) {
        int length;

        if ((str == null) || ((length = str.length()) == 0)) {
            return false;
        }

        for (int i = 0; i < length; i++) {
            if (!Character.isWhitespace(str.charAt(i))) {
                return true;
            }
        }

        return false;
    }
    
    private static Pattern linePattern = Pattern.compile("[_\\W]+(\\w)");
    
    /**
     * 下划线等非字母后第一个字母大写
     * @param str
     * @return
     */
    public static String lineToCamel(String str){
    	if(isBlank(str)){
    		return "";
    	}
//    	str = str.toLowerCase();
    	Matcher matcher = linePattern.matcher(str);
    	StringBuffer sb = new StringBuffer();
    	while(matcher.find()){
    		matcher.appendReplacement(sb, matcher.group(1).toUpperCase());
    	}
    	matcher.appendTail(sb);
    	return sb.toString();
    }
    
    private static Pattern trimLetterPattern = Pattern.compile("[^a-zA-Z]");
    /**
     * 截去前面的所有非字母类字符
     * @param str
     * @return
     */
    public static String trimUntilFirstLetter(String str){
    	if(isBlank(str)){
    		return "";
    	}
    	Matcher matcher = trimLetterPattern.matcher(str);
    	StringBuffer sb = new StringBuffer();
    	while(matcher.find()){
    		matcher.appendReplacement(sb, "");
    	}
    	matcher.appendTail(sb);
    	return sb.toString();
    }
    
    private static Pattern trimNonWordPattern = Pattern.compile("[^a-zA-Z0-9]+");
    /**
     * 截去所有非字母，非数字的字符
     * @param str
     * @return
     */
    public static String trimAllNonWrod(String str){
    	if(isBlank(str)){
    		return "";
    	}
    	Matcher matcher = trimNonWordPattern.matcher(str);
    	StringBuffer sb = new StringBuffer();
    	while(matcher.find()){
    		matcher.appendReplacement(sb, "");
    	}
    	matcher.appendTail(sb);
    	return sb.toString();
    }
    
    /**
     * 转换首字母大小写
     * @param str
     * @param upperCase  为true时转换首字母大写，否则转换首字母小写
     * @return
     */
    public static String convertFristLetterCase(String str, boolean upperCase){
    	if(isBlank(str)){
    		return str;
    	}
    	char[] chs = str.toCharArray();
    	if(upperCase){//首字母大写
    		if (chs[0] >= 'a' && chs[0] <= 'z') {  
    	        chs[0] = (char) (chs[0] - 32);  
    	    }
    	}else{//首字母小写
    		if (chs[0] >= 'A' && chs[0] <= 'Z') {  
    	        chs[0] = (char) (chs[0] + 32);  
    	    }
    	}
    	return new String(chs);
    }
    
    /**
     * 字符串 下划线 转 驼峰
     * @param param
     * @return
     */
    public static String underlineToCamel2(String param){  
        if (param==null||"".equals(param.trim())){  
            return "";  
        }  
        StringBuilder sb=new StringBuilder(param);  
        Matcher mc= Pattern.compile("_").matcher(param);  
        int i=0;  
        while (mc.find()){  
            int position=mc.end()-(i++);  
            //String.valueOf(Character.toUpperCase(sb.charAt(position)));  
            sb.replace(position-1,position+1,sb.substring(position,position+1).toUpperCase());  
        }  
        return sb.toString();
    } 
    
    public static int countByFinder(String regex, String source){
    	if(source == null || source.isEmpty()){
    		return 0;
    	}
    	 Pattern expression = Pattern.compile(regex);
         Matcher matcher = expression.matcher(source);
         int n = 0;
         while(matcher.find()){
        	 n++;
         }
         return n;
    }
    
    /**
     * 字符串解析为Boolean对象
     * <br>
     * str : true   is  true
     * str : false  is  false;
     * other:       is  null
     * @param s
     * @return
     */
    public static Boolean parseBoolean(String s){
    	if("true".equals(s)){
    		return true;
    	}else if("false".equals(s)){
    		return false;
    	}else{
    		return null;
    	}
    }
}
